package org.ala.tiktools.sharddb.mybatis.router.shard_key_router;

import org.ala.tiktools.sharddb.mybatis.router.ShardInfo;
import org.ala.tiktools.tools.kv.Maps;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 利用分片键进行分片的工作者
 *
 * @author ala
 * @date 2025-03-19 09:32
 */
public class ShardKeyRouteWorker {


    static ShardKeyRouteWorker _instance;
    public static ShardKeyRouteWorker instance() {
        if (_instance == null) {
            synchronized (ShardKeyRouteWorker.class) {
                if (_instance == null) {
                    _instance = new ShardKeyRouteWorker();
                }
            }
        }
        return _instance;
    }


    /****************************************************************************************************
     *  分库分表
     ****************************************************************************************************/
    public <E, SK extends IShardKey> Map<ShardInfo, E> route(E e, IShardKeyRouter<SK> router, IShardKeyConverter<E, SK> converter) {
        if (router == null || converter == null) {return null;}

        SK sk = converter.convert(e);
        Map<ShardInfo, SK> map = router.route(sk);
        return Maps.convert(map, _sk -> {
            return converter.deConvert(e, _sk);
        });
    }
    public <E, SK extends IShardKey> Map<ShardInfo, List<E>> route(List<E> es, IShardKeyRouter<SK> router, IShardKeyConverter<E, SK> converter) {
        Map<ShardInfo, List<E>> res = new HashMap<>();
        es.forEach(e -> Maps.appendGroup(res, route(e, router, converter)));
        return res;
    }


}
